package com.zjcode.cdcer.service.impl;

import com.chinatechstar.component.commons.entity.MPage;
import com.chinatechstar.component.commons.result.PaginationBuilder;
import com.chinatechstar.component.commons.service.BaseService;
import com.chinatechstar.component.commons.supports.PageData;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjcode.cdcer.mapper.*;
import com.zjcode.cdcer.model.CerReportProgress;
import com.zjcode.cdcer.model.ZjcodeSysRegion;
import com.zjcode.cdcer.model.CerDetaildataImportInfo;
import com.zjcode.cdcer.model.CerDetaildataImportOfficeInfo;
import com.zjcode.cdcer.pojo.CerSysteminitImportInfo;
import com.zjcode.cdcer.model.CerSysteminitImportOfficialInfo;
import com.zjcode.cdcer.service.CerReportProgressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CerReportProgressServiceImpl implements CerReportProgressService, BaseService {

    @Autowired
    private CerReportProgress2Mapper cerReportProgressMapper;
    //private CerReportProgressMapper cerReportProgressMapper;

    //初始数据上报
    @Autowired
    private CerSysteminitImportInfoMapper cerSysteminitImportInfoMapper;

    //初始数据上报正式库
    @Autowired
    private CerSysteminitImportOfficialInfoMapper cerSysteminitImportOfficialInfoMapper;

    //详情数据上报
    @Autowired
    private CerDetaildataImportInfoMapper cerDetaildataImportInfoMapper;

    //详情数据正式库
    @Autowired
    private CerDetaildataImportOfficeInfoMapper cerDetaildataImportOfficeInfoMapper;

    @Autowired
    private ZjcodeSysRegionMapper zjcodeSysRegionMapper;

    @Override
    public Map<String, Object> listPageData(PageData pageData) {
        // 1-2两步目前以移动到定时任务中执行,执行周期为每天23:30
        ////1.先清空表数据
        //cerReportProgressMapper.deleteAll();
        ////2.调用方法，取出表里最新数据
        //insertData();

        //3.分页数据
        //设置获取分页数据map
        MPage mPage = getPageInfo(pageData);
        Page<Object> page = PageHelper.startPage(mPage.getCurrentPage(), mPage.getPageSize());
        List<LinkedHashMap<String, Object>> mapList = cerReportProgressMapper.listPageData(pageData);
        return PaginationBuilder.buildResult(mapList, page.getTotal(), mPage.getCurrentPage(), mPage.getPageSize(), String.valueOf(pageData.get("type")));
    }

    @Override
    public List<LinkedHashMap<String, Object>> queryAll(PageData pageData) {
        return cerReportProgressMapper.queryAll(pageData);
    }


    /**
     * 详情数据
     *
     * @params systeminitImportOfficialInfos 初始上报正式库
     * @params detaildataImportOfficeInfos 详情数据正式库数据表
     */
    private List<CerReportProgress> handleCerReportProgress_detail(List<CerSysteminitImportOfficialInfo> systeminitImportOfficialInfos, List<CerDetaildataImportOfficeInfo> detaildataImportOfficeInfos) {
        //新建初始数据集合
        List<CerReportProgress> list = new ArrayList<>();

        List<CerDetaildataImportInfo> detaildataImportInfos = cerDetaildataImportInfoMapper.queryAllData();//详情数据上报数据集合

        //处理数据-初始数据上报集合
        List<CerDetaildataImportInfo> infos = handleData_datail(detaildataImportInfos);

        if (!CollectionUtils.isEmpty(infos)) {

            //通过reginCode分组数据
            Map<String, List<CerDetaildataImportInfo>> initial_data_reginCode = infos.parallelStream().collect(Collectors.groupingBy(CerDetaildataImportInfo::getRegionCode));

            initial_data_reginCode.entrySet().stream().forEach(each -> {
                String key = each.getKey();
                List<CerDetaildataImportInfo> values = each.getValue();

                Map<Integer, List<CerDetaildataImportInfo>> initial_data_isHaveError = values.parallelStream().collect(Collectors.groupingBy(CerDetaildataImportInfo::getIsHaveError));

                CerReportProgress record = new CerReportProgress();
                //主键
                record.setId(get32UUID());
                //地区组合编码
                String[] split = key.split("\\|");
                //省份
                record.setProvince_code(split[0]);
                //城市
                record.setCity_code(split[1]);
                //区县
                record.setRegion_code(split[2]);
                //初始数据正式库总量
                int systeminitImportOfficialInfoCount = systeminitImportOfficialInfos.size();
                record.setTotal(Optional.of(systeminitImportOfficialInfoCount).orElse(0));
                //详情数据上报总量-应报数
                int infoCount = infos.size();
                record.setYbs(Optional.of(infoCount).orElse(0));
                //详情数据上报合格/不合格
                //合格数
                List<CerDetaildataImportInfo> qualifieds = initial_data_isHaveError.get(0);
                List<CerDetaildataImportInfo> unQualifieds = initial_data_isHaveError.get(1);
                int qualifiedCount = Optional.ofNullable(qualifieds).orElse(new ArrayList<>()).size();
                //不合格数
                int unQualifiedCount = Optional.ofNullable(unQualifieds).orElse(new ArrayList<>()).size();
                record.setHg(qualifiedCount);
                //详情数据上报不合格-不合格
                record.setBhg(unQualifiedCount);
                //详情数据上报合格率-合格率
                if (qualifiedCount != 0 || unQualifiedCount != 0) {
                    //详情数据上报合格率
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    numberFormat.setMaximumFractionDigits(2);
                    String result = numberFormat.format((float) qualifiedCount / (qualifiedCount + unQualifiedCount) * 100);
                    String pass_rate = result + "%";
                    record.setHgl(pass_rate);
                    //合计-合格率%
                    record.setTotal_hgl(pass_rate);
                } else {
                    record.setHgl("0%");
                    record.setTotal_hgl("0%");
                }
                //详情数据正式库-上报数
                int detaildataImportOfficeInfoCount = detaildataImportOfficeInfos.size();
                record.setSbs(Optional.of(detaildataImportOfficeInfoCount).orElse(0));
                //详情数据上报正式库-占比
                if (detaildataImportOfficeInfoCount != 0 || infoCount != 0) {
                    //详情数据上报正式库占比
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    numberFormat.setMaximumFractionDigits(2);
                    String result = numberFormat.format((float) detaildataImportOfficeInfoCount / (detaildataImportOfficeInfoCount + infoCount) * 100);
                    String proportion = result + "%";
                    record.setZb(proportion);
                    //合计-占比%
                    record.setTotal_zb(proportion);
                } else {
                    record.setZb("0%");
                    record.setTotal_zb("0%");
                }
                //合计-上报数
                record.setTotal_sbs(Optional.of(detaildataImportOfficeInfoCount).orElse(0));
                //合计-合格
                record.setTotal_hg(qualifiedCount);
                //合计-不合格
                record.setTotal_bhg(unQualifiedCount);
                //详情数据类型
                record.setType(2);
                //deleted
                record.setDeleted(0);
                //插入时间
                record.setInsert_datetime(new Date(System.currentTimeMillis()));
                //更新时间
                record.setLast_update_datetime(new Date(System.currentTimeMillis()));
                //ext_flag => 地域数据
                record.setExt_flag(key);
                list.add(record);
            });
        }
        return list;
    }

    /**
     * 初始数据
     *
     * @params detaildataImportOfficeInfos 详情数据正式库数据表
     * @params systeminitImportOfficialInfos 初始上报正式库
     */
    private List<CerReportProgress> handleCerReportProgress_systeminit(List<CerDetaildataImportOfficeInfo> detaildataImportOfficeInfos, List<CerSysteminitImportOfficialInfo> systeminitImportOfficialInfos) {
        //详情数据上报集合
        List<CerReportProgress> list = new ArrayList<>();

        //初始数据
        List<CerSysteminitImportInfo> systeminitImportData = cerSysteminitImportInfoMapper.queryAllData(); //初始数据上报数据集合

        //处理数据-初始数据上报集合
        List<CerSysteminitImportInfo> infos = handleData_systeminit(systeminitImportData);

        if (!CollectionUtils.isEmpty(infos)) {

            //通过reginCode分组数据
            Map<String, List<CerSysteminitImportInfo>> detail_data_reginCode = infos.parallelStream().collect(Collectors.groupingBy(CerSysteminitImportInfo::getRegionCode));

            detail_data_reginCode.entrySet().stream().forEach(each -> {
                String key = each.getKey();
                List<CerSysteminitImportInfo> values = each.getValue();

                Map<Integer, List<CerSysteminitImportInfo>> initial_data_isHaveError = values.parallelStream().collect(Collectors.groupingBy(CerSysteminitImportInfo::getIsHaveError));

                CerReportProgress record = new CerReportProgress();
                //主键
                record.setId(get32UUID());
                //地区组合编码
                String[] split = key.split("\\|");
                //省份
                record.setProvince_code(split[0]);
                //城市
                record.setCity_code(split[1]);
                //区县
                record.setRegion_code(split[2]);
                //详情数据正式库总量
                int detaildataImportOfficeInfoCount = detaildataImportOfficeInfos.size();
                record.setTotal(Optional.of(detaildataImportOfficeInfoCount).orElse(0));
                //初始数据上报总量-应报数
                int infoCount = infos.size();
                record.setYbs(Optional.of(infoCount).orElse(0));
                //初始数据上报 -合格/不合格
                //合格集合
                List<CerSysteminitImportInfo> qualifieds = initial_data_isHaveError.get(0);
                //不合格集合
                List<CerSysteminitImportInfo> unQualifieds = initial_data_isHaveError.get(1);
                int qualifiedCount = Optional.ofNullable(qualifieds).orElse(new ArrayList<>()).size();
                //不合格数
                int unQualifiedCount = Optional.ofNullable(unQualifieds).orElse(new ArrayList<>()).size();
                record.setHg(qualifiedCount);
                //初始数据上报不合格-不合格
                record.setBhg(unQualifiedCount);
                //初始数据上报合格率-合格率
                if (qualifiedCount != 0 || unQualifiedCount != 0) {
                    //初始数据上报合格率
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    numberFormat.setMaximumFractionDigits(2);
                    String result = numberFormat.format((float) qualifiedCount / (qualifiedCount + unQualifiedCount) * 100);
                    String pass_rate = result + "%";
                    record.setHgl(pass_rate);
                    //合计-合格率%
                    record.setTotal_hgl(pass_rate);
                } else {
                    record.setHgl("0%");
                    record.setTotal_hgl("0%");
                }
                //初始数据上报正式库总数-上报数
                int systeminitImportOfficialInfoCount = systeminitImportOfficialInfos.size();
                record.setSbs(Optional.of(systeminitImportOfficialInfoCount).orElse(0));
                //初始数据上报正式库-占比
                if (systeminitImportOfficialInfoCount != 0 || infoCount != 0) {
                    //初始数据上报正式库占比
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    numberFormat.setMaximumFractionDigits(2);
                    String result = numberFormat.format((float) systeminitImportOfficialInfoCount / (systeminitImportOfficialInfoCount + infoCount) * 100);
                    String proportion = result + "%";
                    record.setZb(proportion);
                    //合计-占比%
                    record.setTotal_zb(proportion);
                } else {
                    record.setZb("0%");
                    record.setTotal_zb("0%");
                }
                //合计-上报数
                record.setTotal_sbs(Optional.of(systeminitImportOfficialInfoCount).orElse(0));
                //合计-合格
                record.setTotal_hg(qualifiedCount);
                //合计-不合格
                record.setTotal_bhg(unQualifiedCount);
                //初始数据类型
                record.setType(1);
                //deleted
                record.setDeleted(0);
                //插入时间
                record.setInsert_datetime(new Date(System.currentTimeMillis()));
                //更新时间
                record.setLast_update_datetime(new Date(System.currentTimeMillis()));
                //ext_flag => 地域数据
                record.setExt_flag(key);
                list.add(record);
            });
        }
        return list;
    }

    private List<CerSysteminitImportInfo> handleData_systeminit(List<CerSysteminitImportInfo> list) {
        list.parallelStream().forEach(each -> {
            String provinceId = each.getProvinceId();
            String cityId = each.getCityId();
            String countyId = each.getDistrictId();
            String reginCode = provinceId + "|" + cityId + "|" + countyId;
            each.setRegionCode(reginCode);
        });
        return list;
    }

    private List<CerDetaildataImportInfo> handleData_datail(List<CerDetaildataImportInfo> list) {
        list.parallelStream().forEach(each -> {
            String provinceId = each.getProvinceId();
            String cityId = each.getCityId();
            String countyId = each.getDistrictId();
            String reginCode = provinceId + "|" + cityId + "|" + countyId;
            each.setRegionCode(reginCode);
        });
        return list;
    }

    private List<CerReportProgress> handleReginData(List<CerReportProgress> list) {
        List<ZjcodeSysRegion> regions = zjcodeSysRegionMapper.queryAllReginData();

        list.parallelStream().forEach(each -> {
            String cityId = each.getCity_code();
            String countyId = each.getRegion_code();

            regions.parallelStream().forEach(item -> {
                String code = item.getRegionCode();
                each.setProvince_name("安徽省");
                if (code.equals(cityId)) {
                    each.setCity_name(item.getRegionName());
                }
                if (code.equals(countyId)) {
                    each.setRegion_name(item.getRegionName());
                }
            });
        });
        return list;
    }
}
